const express = require('express');
const router = express.Router();
const db = require('../../db/index.js');
// 图片上传模块
const upload = require('../../lib/upload');
const path = require('path');
const fs = require('fs');
// 分类页面展示
router.get('/classify', (req, res) => {
  res.render('admin/goods_classify');
});
// 商品展示
router.get('/goodsclassify', (req, res) => {
  let isSearch = req.query.search ? req.query.search : '';
  var count;
  const sqlCount = `select count(*) as count from product_classification  where pc_name like "%${isSearch}%" AND is_delete=0`;
  db.query(sqlCount, (err, result) => {
    if (err) {
      //
      return err.message;
    }
    count = result[0].count;
  });
  const { page, limit } = req.query;
  var offset = (page - 1) * limit;

  // res.render('admin/goods_classify');
  // var sql = `SELECT * FROM product_classification`;
  var sql = `SELECT * FROM product_classification WHERE pc_name LIKE '%${isSearch}%'  AND is_delete=0 limit ${offset},${limit}`;

  db.query(sql, (err, results) => {
    if (err) return res.send({ code: '1', msg: err.msg });
    if (results.length != 0) {
      return res.send({ code: '0', msg: '查询成功', data: results, count: count });
    } else {
      return res.send({ code: '1', msg: '查询失败' });
    }
  });
});

// 增加商品分类
router.post('/addpc', (req, res) => {
  // console.log(req.body);
  var sql = `INSERT INTO product_classification(pc_name,pc_sort)  VALUES('${req.body.pc_name}','${req.body.pc_sort}')`;
  db.query(sql, (err, results) => {
    if (err) return res.send({ code: 0, msg: err.message });
    if (results.affectedRows == 1) {
      return res.send({ code: 1, msg: '添加成功' });
    } else {
      return res.send({ code: 0, msg: '添加成功' });
    }
  });
});
// 更新排序
router.get('/pcupdate', (req, res) => {
  // console.log(req.query);
  var sql = `UPDATE  product_classification SET pc_sort=${req.query.pc_sort} WHERE pc_id=${req.query.id}`;
  db.query(sql, (err, results) => {
    if (err) return res.send({ code: 0, msg: '数据库查询发送错误' });
    if (results.affectedRows == 1) {
      // 影响一行 修改成功
      return res.send({ code: 1, msg: '修改成功' });
    } else {
      return res.send({ code: 0, msg: '修改失败' });
    }
  });
});
// 软删除
router.get('/pcdelete', (req, res) => {
  var sql = `UPDATE product_classification SET is_delete=1 WHERE pc_id=${req.query.id}`;
  db.query(sql, (err, results) => {
    if (err) return res.send({ code: 0, msg: err.message });
    if (results.affectedRows == 1) {
      // 数据修改成功
      return res.send({ code: 1, msg: '删除成功' });
    } else {
      return res.send({ code: 0, msg: '删除失败' });
    }
  });
});
// 产品分类的批量删除
router.get('/pcdeleteall', (req, res) => {
  var { ids } = req.query;

  // console.log(ids);
  var idArr = ids.split(',');
  // console.log(idArr);
  idArr.forEach(id => {
    // console.log(id);
    var sql = `DELETE FROM product_classification WHERE pc_id=${id}`;
    db.query(sql, (err, results) => {
      if (err) {
        return res.send({ code: 0, msg: err.message });
      }
      // 产品分类  没有图片！！！！！
      // if (results.affectedRows == 1) {
      //   // 影响行数等于一行  数据库删除了  然后去删除图片
      //   fs.unlink(img_url, err => {
      //     if (err) return res.send({ code: 0, msg: '多图删除失败' });
      //   });
      // }
    });
  });
  res.send({ code: 1, msg: '删除成功' });
});
// 修改获取数据
router.get('/updateall', (req, res) => {
  var sql = `select * from product_classification where pc_id=${req.query.id}`;
  db.query(sql, (err, results) => {
    if (err) return res.send({ code: 0, msg: err.message });
    if (results.length != 0) {
      // 数据查询成功
      return res.send({ code: 1, msg: '删除成功', data: results[0] });
    } else {
      return res.send({ code: 0, msg: '删除失败' });
    }
  });
});
// 提交修改的路由
router.post('/updateall', (req, res) => {
  // console.log(req.body); // {
  //   pc_id: '11',
  //   pc_name: '人工智能22',
  //   pc_sort: '133'
  // }
  var sql = `UPDATE product_classification SET pc_name='${req.body.pc_name}',pc_sort=${req.body.pc_sort} WHERE pc_id=${req.body.pc_id}`;
  db.query(sql, (err, results) => {
    if (err) return res.send({ code: 0, msg: err.message });
    if (results.affectedRows == 1) {
      // 数据查询成功
      return res.send({ code: 1, msg: '修改成功' });
    } else {
      return res.send({ code: 0, msg: '修改失败' });
    }
  });
});
//

// 上传图片的路由
router.post('/upload', upload.single('file'), (req, res) => {
  res.send({
    code: 1,
    url: '/admin/uploads/' + req.file.filename,
  });
});
// 添加产品展示页
router.get('/add', (req, res) => {
  const sql = `select * from product_classification WHERE is_delete=0`;
  db.query(sql, (err, results) => {
    if (err) {
      throw err.message;
    }
    res.render('admin/product_add', { classification: results });
  });
});
// post  添加产品
router.post('/insert', (req, res) => {
  var { pc_id, pi_name, pi_title, pi_img, pi_banner, pi_thumb, pi_content } = req.body;
  var sql = `INSERT INTO product_information_management(pc_id,pi_name,pi_title, pi_img, pi_banner, pi_thumb, pi_content) VALUES(?,?,?,?,?,?,?)`;

  db.query(
    sql,
    [pc_id, pi_name, pi_title, pi_img, pi_banner, pi_thumb, pi_content],
    (err, results) => {
      if (err) {
        // 数据库操作失败
        return res.send({
          code: 0,
          msg: err.message,
        });
      }

      if (results.affectedRows == 1) {
        // 影响了一行  说明 数据插入成功
        return res.send({
          code: 1,
          msg: '数据插入成功',
        });
      } else {
        return res.send({
          code: 0,
          msg: '数据插入失败',
        });
      }
    }
  );
});
// 产品详情
router.get('/details', (req, res) => {
  res.render('admin/product_details');
});
// 产品渲染表格
router.get('/list', (req, res) => {
  // res.render('admin/product_details');
  let isSearch = req.query.search ? req.query.search : '';
  var count;
  const sqlCount = `select count(*) as count from product_information_management  where pi_name like "%${isSearch}%"`;
  db.query(sqlCount, (err, result) => {
    if (err) {
      //
      return err.message;
    }
    // console.log(result); //[ { count: 12 } ]
    // console.log(result[0].count);//12
    count = result[0].count;
  });
  const { page, limit } = req.query;
  var offset = (page - 1) * limit;
  // var sql = `SELECT * FROM product_information_management WHERE pi_name LIKE '%${isSearch}%' limit ${offset},${limit}`;
  var sql = `SELECT * FROM product_information_management INNER JOIN product_classification ON product_information_management.pc_id=product_classification.pc_id WHERE  product_information_management.is_delete=0 AND   pi_name LIKE '%${isSearch}%' limit ${offset},${limit}`;
  // SELECT * FROM product_information_management INNER JOIN product_classification ON product_information_management.pc_id=product_classification.pc_id
  db.query(sql, (err, results) => {
    // console.log(results);
    if (err) return res.send({ code: 1, msg: err.message });
    if (results.length != 0) {
      return res.send({ code: 0, msg: '查询成功', data: results, count: count });
    } else {
      return res.send({ code: 1, msg: '查询失败' });
    }
  });
});
// 查询

// 产品的批量删除deletecheck
router.get('/deletecheck', (req, res) => {
  // res.render('admin/product_details');
  // console.log(req.query);//{ ids: '1,2,3,4' }
  // res.send('get  多个删除');
  var { ids } = req.query;

  // console.log(ids);
  var idArr = ids.split(',');

  // console.log(idArr);
  idArr.forEach(id => {
    // 查询数据库

    var imgSql = `SELECT * FROM product_information_management WHERE pi_id=${id}`;
    var img;
    var banner;
    var pi_thumb;
    db.query(imgSql, (err, results) => {
      if (err) {
        return res.send({ code: 0, msg: err.message });
      }
      if (results !== 0) {
        img = results[0].pi_img;
        banner = results[0].pi_banner;
        pi_thumb = results[0].pi_thumb;

        // 删除数据库
        // var sql = `UPDATE product_information_management SET is_delete=1 WHERE pi_id=${id}`;
        var sql = `DELETE FROM product_information_management WHERE pi_id=${id}`;
        db.query(sql, (err, results) => {
          if (err) {
            return res.send({ code: 0, msg: err.message });
          }
          if (results.affectedRows == 1) {
            // 数据库删除成功
            if (img) {
              // 如果图片存在TODO
              const img_url = path.join(__dirname, '../../static', img);
              fs.unlink(img_url, err => {
                if (err) return res.send({ code: 0, msg: '图片删除失败' });
              });
            }
            if (banner) {
              const img_url = path.join(__dirname, '../../static', banner);
              fs.unlink(img_url, err => {
                if (err) return res.send({ code: 0, msg: '图片删除失败' });
              });
            }
            if (pi_thumb) {
              pi_thumb = pi_thumb.split(',');
              pi_thumb.forEach(item => {
                const img_url = path.join(__dirname, '../../static', item);
                fs.unlink(img_url, err => {
                  if (err) return res.send({ code: 0, msg: '图片删除失败' });
                });
              });
            }
          }
        });
      }
    });
  });
  res.send({ code: 1, msg: '删除成功' });
});

router.get('/read', (req, res) => {
  var sql = `SELECT * FROM product_information_management INNER JOIN product_classification ON product_information_management.pc_id=product_classification.pc_id WHERE  product_information_management.pi_id=${req.query.id}`;
  db.query(sql, (err, results) => {
    // console.log(results);
    if (err) {
      return res.send({ code: 0, msg: err.message });
    }
    if (results.length != 0) {
      res.render('admin/product_read', { data: results[0] });
    } else {
      return res.send({ code: 0, msg: '查询失败' });
    }
  });
  // console.log(req.query);
  // res.render('admin/product_read');
});
// 商品修改页面

// 商品修改
router.get('/update', (req, res) => {
  // res.send('update');
  var project_list;
  var project_class;
  var sql = `SELECT * FROM product_information_management INNER JOIN product_classification ON product_information_management.pc_id=product_classification.pc_id WHERE  product_information_management.pi_id=${req.query.id}`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 0, msg: err.message });
    }
    if (results.length != 0) {
      // 查到了数据
      project_list = results[0];
      // res.render('admin/product_update', { data: results[0] });
    } else {
      return res.send({ code: 0, msg: '查询失败' });
    }
  });
  var sql2 = `SELECT * FROM product_classification`;
  db.query(sql2, (err, results) => {
    if (err) {
      return res.send({ code: 0, msg: err.message });
    }
    if (results.length != 0) {
      // 查到了数据
      project_class = results;
      // res.render('admin/product_update', { data: results[0] });
    } else {
      return res.send({ code: 0, msg: '查询失败' });
    }
  });
  setTimeout(() => {
    res.render('admin/product_update', { data: project_list, project_class:project_class });
  }, 500);
});
// 商品修改提交
router.post('/update', (req, res) => {
  // console.log(req.body);
  var {
    pi_id,
    pi_name,
    pc_id,
    pi_title,
    pi_content,
    is_delete,
    new_pi_img,
    old_pi_img,
    new_pi_banner,
    old_pi_banner,
    new_pi_thumb,
    old_pi_thumb,
  } = req.body;
  is_delete = is_delete ? is_delete : 0;
  // 1表示删除  0表示未删除
  // if (new_pi_thumb != '' && new_pi_banner != '' && new_pi_img != '') {
  // 说明三个数据全部上传了
  // 替换数据库中的数据 然后删除图片
  var sql = `update product_information_management set pc_id=?,pi_name=?,pi_title=?, pi_content=?,is_delete=?,pi_img=?,pi_banner=?,pi_thumb=? where pi_id=?`;
  db.query(
    sql,
    [
      pc_id,
      pi_name,
      pi_title,
      pi_content,
      is_delete,
      new_pi_img,
      new_pi_banner,
      new_pi_thumb,
      pi_id,
      old_pi_img,
      old_pi_banner,
      old_pi_thumb,
    ],
    (err, results) => {
      if (err) return res.send({ code: 0, msg: err.message });
      if (results.affectedRows == 1) {
        // 影响一行  数据库操作成功
        if (new_pi_img != old_pi_img) {
          // 说明修改了图片
          const img_url = path.join(__dirname, '../../static', old_pi_img);
          fs.unlink(img_url, err => {
            if (err) return res.send({ code: 0, msg: '图片删除失败' });
          });
        }
        if (new_pi_banner != old_pi_banner) {
          // 说明修改了图片
          const img_url = path.join(__dirname, '../../static', old_pi_banner);
          fs.unlink(img_url, err => {
            if (err) return res.send({ code: 0, msg: '轮播图删除失败' });
          });
        }
        if (new_pi_thumb != old_pi_thumb) {
          // 说明修改了图片
          const img_url = path.join(__dirname, '../../static', old_pi_thumb);
          fs.unlink(img_url, err => {
            if (err) return res.send({ code: 0, msg: '多图删除失败' });
          });
        }
        return res.send({ code: 1, msg: '修改成功' });
      } else {
        return res.send({ code: 0, msg: '修改失败' });
      }
    }
  );
});

// 商品删除
router.get('/delete', (req, res) => {
  // console.log(req.query.id);
  var sql = `update product_information_management set is_delete=1 where pi_id=${req.query.id}`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 0, msg: err.message });
    }
    if (results.affectedRows == 1) {
      return res.send({ code: 1, msg: '删除成功' });
    } else {
      return res.send({ code: 0, msg: '删除失败' });
    }
  });
});
module.exports = router;
